import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  UseInterceptors,
  UploadedFile,
  Req,
  Query,
} from "@nestjs/common";
import { UploadService } from "./upload.service";
import { CreateUploadDto } from "./dto/create-upload.dto";
import { UpdateUploadDto } from "./dto/update-upload.dto";
import { FileInterceptor } from "@nestjs/platform-express";
import { Express } from "express";
import * as multer from "multer";
import { join } from "path";
import * as fs from "fs";
import { DateUtils } from "../../utils/date-utils";
import * as path from "path";
import { BaseConfig } from "../../utils/config-utils";
import { FileDto } from "./dto/FileDto";

// 允许的文件扩展名列表
const allowedFileTypes = /jpeg|jpg|png|mp4|gif/;

// 控制器拦截器方法
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const dirName = DateUtils.formatToYYYYMMDD(new Date());
    const ServicePath = `/public/uploads/${dirName}`;
    const folderPath = join(__dirname, `..${ServicePath}`);
    if (!fs.existsSync(folderPath)) {
      fs.mkdirSync(folderPath, { recursive: true });
    }
    cb(null, folderPath);
  },
  filename: (req, file, cb) => {
    // 获取文件的后缀名
    const fileExtension = path.extname(file.originalname).toLowerCase();
    // 检查文件扩展名是否在允许的列表中
    if (!allowedFileTypes.test(fileExtension.slice(1))) {
      return cb(new Error("不支持的文件类型!"), file.originalname);
    }
    // 使用当前时间戳和原始文件名（不带扩展名）以及文件扩展名来创建新的文件名
    const newFileName =
      Date.now() + "_" + BaseConfig.getRandomInt(10000, 99999) + fileExtension;
    cb(null, newFileName);
  },
});

// 设置文件上传大小限制（例如，限制为 50MB）
const fileSizeLimit = BaseConfig.getConfig("FILE_SIZE_LIMIT");

// https://blog.csdn.net/w84647517/article/details/135866668
@Controller("upload")
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}

  @Post("addFile")
  @UseInterceptors(
    FileInterceptor("file", {
      storage,
      limits: {
        fileSize: fileSizeLimit, // 设置文件大小限制
      },
    }),
  )
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  addFile(@UploadedFile() file: Express.Multer.File, @Req() request: any) {
    console.log(file, "addFile");
    const createUploadDto = new CreateUploadDto();
    createUploadDto.file_originalname = file.originalname;
    createUploadDto.file_name = file.filename;
    createUploadDto.file_size = file.size;
    createUploadDto.file_type = file.mimetype;
    createUploadDto.is_active = 1;
    createUploadDto.uploader_id = request["user"]?.id || 0;
    const fullPath = file.path;
    const startIndex = fullPath.lastIndexOf("/public/");
    const relativePath = fullPath.slice(startIndex);
    createUploadDto.file_path = relativePath;
    return this.uploadService.create(createUploadDto);
  }

  /*
   * 根据文件id返回文件
   * */
  @Get("findFileById")
  findFileById(@Query() fileDto: FileDto) {
    return this.uploadService.findOne(fileDto);
  }
}
